package com.example.studentknowledge.repository;

import com.example.studentknowledge.entity.PointRecord;
import com.example.studentknowledge.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 积分记录Repository接口
 */
@Repository
public interface PointRecordRepository extends JpaRepository<PointRecord, Long> {
    
    /**
     * 根据用户查找积分记录
     */
    Page<PointRecord> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
    
    /**
     * 根据积分类型查找记录
     */
    Page<PointRecord> findByTypeOrderByCreatedAtDesc(PointRecord.PointType type, Pageable pageable);
    
    /**
     * 根据用户和积分类型查找记录
     */
    Page<PointRecord> findByUserAndTypeOrderByCreatedAtDesc(User user, PointRecord.PointType type, Pageable pageable);
    
    /**
     * 根据时间范围查找积分记录
     */
    @Query("SELECT p FROM PointRecord p WHERE p.createdAt BETWEEN :startDate AND :endDate ORDER BY p.createdAt DESC")
    List<PointRecord> findByCreatedAtBetween(@Param("startDate") LocalDateTime startDate, @Param("endDate") LocalDateTime endDate);
    
    /**
     * 根据用户和时间范围查找积分记录
     */
    @Query("SELECT p FROM PointRecord p WHERE p.user = :user AND p.createdAt BETWEEN :startDate AND :endDate ORDER BY p.createdAt DESC")
    List<PointRecord> findByUserAndCreatedAtBetween(@Param("user") User user, @Param("startDate") LocalDateTime startDate, @Param("endDate") LocalDateTime endDate);
    
    /**
     * 统计用户的总积分变化
     */
    @Query("SELECT SUM(p.points) FROM PointRecord p WHERE p.user = :user")
    Integer sumPointsByUser(@Param("user") User user);
    
    /**
     * 统计用户在指定时间范围内的积分变化
     */
    @Query("SELECT SUM(p.points) FROM PointRecord p WHERE p.user = :user AND p.createdAt BETWEEN :startDate AND :endDate")
    Integer sumPointsByUserAndDateRange(@Param("user") User user, @Param("startDate") LocalDateTime startDate, @Param("endDate") LocalDateTime endDate);
    
    /**
     * 根据关联对象ID和类型查找记录
     */
    List<PointRecord> findByReferenceIdAndType(Long referenceId, PointRecord.PointType type);
    
    /**
     * 检查用户今日是否已有登录积分记录
     */
    @Query("SELECT COUNT(p) > 0 FROM PointRecord p WHERE p.user = :user AND p.type = 'DAILY_LOGIN' AND DATE(p.createdAt) = CURRENT_DATE")
    boolean existsTodayLoginRecord(@Param("user") User user);
    
    /**
     * 获取积分变化统计（按类型分组）
     */
    @Query("SELECT p.type, SUM(p.points), COUNT(p) FROM PointRecord p WHERE p.user = :user GROUP BY p.type")
    List<Object[]> getPointStatisticsByUser(@Param("user") User user);
}